//
//  AppDelegate.m
//  HNJYB
//
//  Created by Mag1cPanda on 16/7/28.
//  Copyright © 2016年 Mag1cPanda. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "NavViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>         //引入base相关所有的头文件
#import "BaiduMobStat.h"
#import "DESCript.h"
#import "JCAlertView.h"
#import "AvoidCrash.h"
#import "NSDate+Extension.h"
#import "PermissionManager.h"
#import "IQKeyboardManager.h"

@interface AppDelegate ()
{
    JCAlertView *updateAlert;
    NSString *localVersion;//本地版本
    NSString *appStoreUrl;//AppStore链接
    BOOL isLocated;
    
}
@property (nonatomic, strong) UIAlertView *alert;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    //适配ios11
    if (@available(ios 11.0,*)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        UITableView.appearance.estimatedRowHeight = 0;
        UITableView.appearance.estimatedSectionFooterHeight = 0;
        UITableView.appearance.estimatedSectionHeaderHeight = 0;
    }
    
    [AvoidCrash becomeEffective];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    
    //更新提示
    [self checkVersion];
    
    //百度统计
    [self registerBaiduStatistiCal];

    // 要使用百度地图，请先启动BaiduMapManager
    BMKMapManager *_mapManager = [[BMKMapManager alloc] init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    
    NSString *BundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    BOOL ret;
    
    if ([BundleId isEqualToString:@"com.Longrise.HNJYB"]) {
        //企业
        ret = [_mapManager start:@"g4sxtWpGAWz6hPkoNtFnYVGEhoZKEFCu" generalDelegate:nil];
    }
    
    else {
        //商店
        ret = [_mapManager start:@"41lRufAbpqk5ygG3Y8pkS285vGeo3tun" generalDelegate:nil];
    }

    if (!ret)
    {
        NSLog(@"manager 启动失败");
    }

    //请求权限
    [[PermissionManager getPermissionManager] requestLocationPermissionBlock:^(BOOL b) {
        
    }];
    
    
    //初始化BMKLocationService
//    _locService = [[BMKLocationService alloc] init];

    //给账户在其他地方登陆的通知添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AccountLoginInOtherPlace:) name:@"LoginOutNotifaction" object:nil];

    NavViewController *nav = [[NavViewController alloc] init];
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [nav pushViewController:loginVC animated:YES];
    self.window.rootViewController = nav;
    self.window.backgroundColor = [UIColor whiteColor];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSLog(@"applicationWillResignActive");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"applicationDidEnterBackground");
    
   
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"applicationWillEnterForeground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"applicationDidBecomeActive");
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"applicationWillTerminate");
}



#pragma mark - 检测版本更新
-(void)checkVersion{
    
    //获取本地版本
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *tmp = [infoDic objectForKey:@"CFBundleShortVersionString"];
    
    localVersion = [tmp stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSLog(@"localVersion -> %@",localVersion);
    
    //获取后台的版本
    NSString *urlString = @"http://jgkckp.henanga.gov.cn/restservices";
    
    NSMutableDictionary *bean = [NSMutableDictionary dictionary];
    [bean setValue:@"HNJT_JJAPP_IOS" forKey:@"appname"];
    
    
    [LSHttpManager requestUrl:urlString serviceName:@"appgetversion/lbcp_getAppVersion" parameters:bean complete:^(id result, ResultType resultType) {
        
        NSLog(@"版本数据 -> %@",result);
        
        if (result) {
            NSString *storeVersion;
            storeVersion = result[@"appversion"];
            NSLog(@"version ~ %@",storeVersion);
            
            if ([localVersion floatValue] < [storeVersion floatValue]) {
                
                [self showUpdateAlert];
                
            }
        }
        
    }];
    
}

- (void)showUpdateAlert
{
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 60, 200)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.layer.cornerRadius = 5;
    customView.clipsToBounds = YES;
    
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(customView.width / 2 - 30, 20, 60, 60)];
    icon.image = [UIImage imageNamed:@"warn"];
    [customView addSubview:icon];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + 20, customView.width, 20)];
    lab.font = HNFont(14);
    lab.text = @"有新的版本，请及时更新。";
    lab.textColor = [UIColor darkGrayColor];
    lab.textAlignment = NSTextAlignmentCenter;
    [customView addSubview:lab];
    
    UIView *horizontalLine = [[UIView alloc] initWithFrame:CGRectMake(0, lab.maxY + 20, customView.width, 1)];
    horizontalLine.backgroundColor = RGB(235, 235, 235);
    [customView addSubview:horizontalLine];
    
    UIColor *color = [UIColor blackColor];
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(0, lab.maxY + 21, customView.width, 60);
    [confirmBtn setTitle:@"确认" forState:0];
    [confirmBtn setTitleColor:color forState:0];
    [confirmBtn addTarget:self action:@selector(jumpToSafari) forControlEvents:1 << 6];
    [customView addSubview:confirmBtn];
    
    updateAlert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:false];
    [updateAlert show];
}

- (void)jumpToSafari
{
    appStoreUrl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=1168266059"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreUrl]];
}

#pragma mark - 百度统计注册
- (void)registerBaiduStatistiCal
{
    BaiduMobStat *statTracker = [BaiduMobStat defaultStat];
    // 此处(startWithAppId之前)可以设置初始化的可选参数，具体有哪些参数，可详见BaiduMobStat.h文件，例如：
    statTracker.shortAppVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    statTracker.enableDebugOn = NO;
    
    [statTracker startWithAppId:@"a62c6fb82c"];//设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
}

#pragma mark - 用户账号被挤
- (void)AccountLoginInOtherPlace:(NSNotification *)notification
{
    NSLog(@"AccountLoginInOtherPlace");
    NSLog(@"账户被挤掉 ~ %@", [Util objectToJson:notification.object]);
    NSDictionary *dic = notification.object;
    if ([dic[@"restate"] isEqualToString:@"-4"])
    {
    }
    
    if (!_alert)
    {
        _alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的账号已在其他设备登录，如非本人操作，请及时更改密码！" delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"重新登录", nil];
        [_alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //退出
        NavViewController *nav = [[NavViewController alloc] init];
        [nav pushViewController:[[LoginViewController alloc] init] animated:YES];
        self.window.rootViewController = nav;
    }
    else
    {
        //确定
        NSMutableDictionary *bean = [NSMutableDictionary dictionary];
        
        NSString *userflag = GlobleInstance.userflag;
        NSString *password = [UserDefaultsUtil getDataForKey:@"password"];
        NSString *encryptPwd = [DESCript encrypt:password encryptOrDecrypt:kCCEncrypt key:[Util getKey]];
        NSLog(@"重新登录密码：%@", password);
        [bean setValue:userflag forKey:@"userflag"];
        [bean setValue:encryptPwd forKey:@"password"];
        
        [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjapplogin" parameters:bean complete:^(id result, ResultType resultType) {
            
            NSLog(@"重新登录 -> %@", result);
            
            if ([result[@"restate"] isEqualToString:@"1"])
            {
                GlobleInstance.loginData = result[@"data"];
                GlobleInstance.token = result[@"data"][@"token"];
                GlobleInstance.userflag = result[@"data"][@"userinfo"][@"userflag"];
                GlobleInstance.userid = result[@"data"][@"userinfo"][@"id"];
                GlobleInstance.cardno = result[@"data"][@"userinfo"][@"cardno"];
                GlobleInstance.armyname = result[@"data"][@"userinfo"][@"name"];
                GlobleInstance.policeno = result[@"data"][@"userinfo"][@"usercode"];
                GlobleInstance.showname = result[@"data"][@"userinfo"][@"showname"];
                GlobleInstance.photo = result[@"data"][@"userinfo"][@"photo"];
                GlobleInstance.mobilephone = result[@"data"][@"userinfo"][@"mobilephone"];
            }
            else
            {
                SHOWALERT(result[@"redes"]);
            }
            
        }];
    }
}

@end
